import flash.events.MouseEvent;
class VideoPlayer extends flash.display.Sprite
{
	var ns:flash.net.NetStream;
	var logOutput:fl.controls.TextArea;
	var player: flash.media.Video;
	var background:flash.display.Sprite;
	var log:String->Void;
	var url:String;
	public function new(nc:flash.net.NetConnection, url, log)
	{
		super();
		
		addEventListener(flash.events.Event.ADDED_TO_STAGE, onAddedToStage);
		
		this.url = url;
		this.log = log;
		
		createView();
		if(nc.connected)
		{
			ns = new flash.net.NetStream(nc);
			ns.bufferTime = 2.0;
			ns.client=this;
			ns.addEventListener(flash.events.NetStatusEvent.NET_STATUS, onStatus);
			ns.addEventListener(flash.events.AsyncErrorEvent.ASYNC_ERROR, onAsyncError); 
			ns.play(url);
			
			player.attachNetStream(ns);
			
		}
		else
		{
			log("NetConnection is no longer connected");
		}
	}
	function onAsyncError(event:flash.events.AsyncErrorEvent):Void
	{
		log(this.url+": ns async) text="+event.text+", error=" + event.error);
	}
	function onStatus(event:flash.events.NetStatusEvent):Void
	{
		log(this.url+": ns status) code="+event.info.code+ if(event.info.description!=null)", description=" + event.info.description else "");
		log(ns.info.toString().split(" ").join("\n"));
	}
	function onMetaData(data)
	{
		log(this.url+": ns meta");
		for(i in Reflect.fields(data))
			log(i+"="+Reflect.field(data, i));
		if(data.width>0 && data.height>0)
			resize(data.width, data.height);
		var info = ns.info;
	}
	function createView()
	{
		background = new flash.display.Sprite();
		background.buttonMode=true;
		addChild(background);
		background.addEventListener(MouseEvent.MOUSE_DOWN, onStartDrag);
		
		player = new flash.media.Video();
		player.x=player.y=10;
		addChild(player);
		
		resize(player.width, player.height);
	}
	function onStartDrag(event:MouseEvent):Void
	{
		flash.Lib.current.stage.addEventListener(MouseEvent.MOUSE_UP, onStopDrag);
		event.currentTarget.parent.startDrag();
	}
	function onStopDrag(event:MouseEvent):Void
	{
		this.stopDrag();
		flash.Lib.current.stage.removeEventListener(MouseEvent.MOUSE_UP, onStopDrag);
	}
	function onAddedToStage(?event=null)
	{
		positionMiddle(this);
	}
	function positionMiddle(obj:Dynamic)
	{
		obj.x = (flash.Lib.current.stage.stageWidth - obj.width)/2;
		obj.y = (flash.Lib.current.stage.stageHeight - obj.height)/2;
	}
	function resize(w, h):Void
	{
		player.width=w;
		player.height=h;
		
		background.graphics.clear();
		background.graphics.beginFill(0xDDDDFF, 1.0);
		background.graphics.drawRoundRect(0,0,w+20,h+20, 10,10);
		positionMiddle(this);
	}
}
